#include "studyregisterwidget.h"
#include "ui_studyregisterwidget.h"

#include "../MainStation/mainwindow.h"
#include "../Worklist/patientselectdialog.h"
#include "wlistsourcemodel.h"
#include "wlisttableview.h"
#include "sortfilterproxymodel.h"
#include "worklistdialog.h"
#include "wlscpthread.h"
#include "wlistpatient.h"
#include "customizecolumndialog.h"

#include "dcmtk/dcmdata/dcuid.h"

#include <QMessageBox>
#include <QDir>
#include <QSettings>

StudyRegisterWidget::StudyRegisterWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::StudyRegisterWidget)
{
    ui->setupUi(this);
    init();
    createConnections();
}

StudyRegisterWidget::~StudyRegisterWidget()
{
    wlScpThread->terminate();
    delete ui;
}

void StudyRegisterWidget::init()
{
    QSettings s;
    QStringList strlist = s.value(REQ_PHYSICIANS).toStringList();
    strlist.prepend("");
    ui->reqPhysicianCombo->addItems(strlist);

    QString dbpath = QString("%1/%2").arg(mainWindow->getDbConfig().imagePath,
                                          mainWindow->getStationInfo().aetitle);
    QDir().mkpath(dbpath);
    QFile lockfile(QString("%1/%2").arg(dbpath, "lockfile"));
    if (lockfile.open(QFileDevice::WriteOnly)) {
        lockfile.close();
    } else {
        QMessageBox::critical(this, windowTitle(),
                              tr("Database lockfile create failed, try another folder please."));
    }

    wlScpThread = new WLScpThread(mainWindow->getDbConfig().imagePath, mainWindow->getStationInfo().wlistPort, this);
    //connect(wlScpThread, SIGNAL(started()), this, SLOT(onWLScpStarted()));
    //connect(wlScpThread, SIGNAL(finished()), this, SLOT(onWLScpStopped()));
    connect(wlScpThread, SIGNAL(scpError(QString)), mainWindow, SIGNAL(statusBarMsg(QString)));
    wlScpThread->start();

    wlistView = new WlistTableView;
    sourceModel = new WListSourceModel(this);
    proxyModel = new SortFilterProxyModel(this);
    ui->verticalLayout->insertWidget(2, wlistView);
    proxyModel->setSourceModel(sourceModel);
    wlistView->setModel(proxyModel);

    QSettings settings;
    wlistView->setColumnHidden(WListPatient::AccNumber, !settings.value(ACCNUMBER_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::PatientID, !settings.value(PATIENTID_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::PatientName, !settings.value(PATIENTNAME_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::PatientSex, !settings.value(PATIENTSEX_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::PatientBirth, !settings.value(PATIENTBIRTH_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::ReqPhysician, !settings.value(REQPHYSICIAN_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::ReqProcID, !settings.value(REQPROCID_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::ReqProcDesc, !settings.value(REQPROCDESC_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::ReqProcPrio, !settings.value(REQPROCPRIO_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::Modality, !settings.value(MODALITY_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::SchPhysician, !settings.value(SCHPHYSICIAN_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::SchStationAE, !settings.value(SCHSTATIONAE_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::SchStationName, !settings.value(SCHSTATIONNAME_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::SchDateTime, !settings.value(SCHDATETIME_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::SchProcStepDesc, !settings.value(SCHPROCSTEPDESC_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::SchProcStepID, !settings.value(SCHPROCSTEPID_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::AdmissionID, !settings.value(ADMISSIONID_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::Department, !settings.value(DEPARTMENT_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::PatientSize, !settings.value(PATIENTSIZE_COL, 0).toBool());
    wlistView->setColumnHidden(WListPatient::PatientWeight, !settings.value(PATIENTWEIGHT_COL, 0).toBool());
    wlistView->setColumnHidden(WListPatient::PatientPhone, !settings.value(PATIENTPHONE_COL, 0).toBool());
    wlistView->setColumnHidden(WListPatient::PatientAddress, !settings.value(PATIENTADDR_COL, 0).toBool());
    wlistView->setColumnHidden(WListPatient::CreationDateTime, !settings.value(CREATIONTIME_COL, 1).toBool());
    wlistView->setColumnHidden(WListPatient::LastModifiedDateTime, !settings.value(MODIFICATIONTIME_COL, 1).toBool());

    onWlistToday();
}

void StudyRegisterWidget::onNewPatient()
{
    WListPatient *patient = new WListPatient;
    WorkListDialog dialog(patient, WorkListDialog::NewPatient, this);
    if (dialog.exec() == QDialog::Accepted) {
        sourceModel->insertPatient(patient, 0);
    } else {
        delete patient;
    }
}

void StudyRegisterWidget::onNewStudy(const QModelIndex &index)
{
    QModelIndex index_s = proxyModel->mapToSource(index);
    if (index_s.isValid()) {
        WListPatient *study = static_cast<WListPatient*>(index_s.internalPointer());
        WListPatient *newStudy = new WListPatient(*study);
        WorkListDialog dialog(newStudy, WorkListDialog::NewStudy, this);
        if (dialog.exec() == QDialog::Accepted) {
            sourceModel->insertPatient(newStudy);
        } else {
            delete newStudy;
        }
    }
}

void StudyRegisterWidget::onChangeStudy(const QModelIndex &index)
{
    QModelIndex index_s = proxyModel->mapToSource(index);
    if (index_s.isValid()) {
        WListPatient *patient = static_cast<WListPatient*>(index_s.internalPointer());
        WorkListDialog dialog(patient, WorkListDialog::ChangeStudy, this);
        if (dialog.exec() == QDialog::Accepted) {
            sourceModel->setData(index_s, QVariant(), Qt::DisplayRole);
        }
    }
}

void StudyRegisterWidget::onRemoveStudy(const QModelIndex &index)
{
    QModelIndex index_s = proxyModel->mapToSource(index);
    if (index_s.isValid()) {
        if (QMessageBox::warning(this, tr("Remove Patient Entry"),
                                 tr("Are you sure to remove this study?"),
                                 QMessageBox::Ok|QMessageBox::Cancel) == QMessageBox::Ok)
            sourceModel->removeRow(index_s.row());
    }
}

void StudyRegisterWidget::onFromDateChecked(bool checked)
{
    if (checked) proxyModel->setFromDateTime(ui->fromDateTimeEdit->dateTime());
    else proxyModel->setFromDateTime(QDateTime());
}

void StudyRegisterWidget::onToDateChecked(bool checked)
{
    if (checked) proxyModel->setToDateTime(ui->toDateTimeEdit->dateTime());
    else proxyModel->setToDateTime(QDateTime());
}

void StudyRegisterWidget::onColumnCustomise()
{
    CustomizeColumnDialog dialog(wlistView, this);
    dialog.exec();
}

void StudyRegisterWidget::setPermissions()
{
    GroupPermissions perm = mainWindow->getCurrentGroup().permissions;

}

void StudyRegisterWidget::createConnections()
{
    connect(ui->todayButton, SIGNAL(clicked()), this, SLOT(onWlistToday()));
    connect(ui->thisWeekButton, SIGNAL(clicked()), this, SLOT(onWlistThisWeek()));
    connect(ui->thisMonthButton, SIGNAL(clicked()), this, SLOT(onWlistThisMonth()));
    connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(onWlistClear()));
    connect(ui->newPatientButton, SIGNAL(clicked()), this, SLOT(onNewPatient()));
    connect(ui->customizeColumnButton, SIGNAL(clicked()), this, SLOT(onColumnCustomise()));

    connect(wlistView, SIGNAL(newPatient()), this, SLOT(onNewPatient()));
    connect(wlistView, SIGNAL(newStudy(QModelIndex)), this, SLOT(onNewStudy(QModelIndex)));
    connect(wlistView, SIGNAL(changeStudy(QModelIndex)), this, SLOT(onChangeStudy(QModelIndex)));
    connect(wlistView, SIGNAL(removeStudy(QModelIndex)), this, SLOT(onRemoveStudy(QModelIndex)));

    connect(ui->fromCheck, SIGNAL(toggled(bool)), this, SLOT(onFromDateChecked(bool)));
    connect(ui->toCheck, SIGNAL(toggled(bool)), this, SLOT(onToDateChecked(bool)));
    connect(ui->fromDateTimeEdit, SIGNAL(dateTimeChanged(QDateTime)), proxyModel, SLOT(setFromDateTime(QDateTime)));
    connect(ui->toDateTimeEdit, SIGNAL(dateTimeChanged(QDateTime)), proxyModel, SLOT(setToDateTime(QDateTime)));
    connect(ui->patientIdEdit, SIGNAL(textEdited(QString)), proxyModel, SLOT(setPatientID(QString)));
    connect(ui->patientNameEdit, SIGNAL(textEdited(QString)), proxyModel, SLOT(setPatientName(QString)));
    connect(ui->reqPhysicianCombo, SIGNAL(currentTextChanged(QString)), proxyModel, SLOT(setReqPhysician(QString)));
}

void StudyRegisterWidget::onWlistToday()
{
    ui->fromCheck->setChecked(true);
    ui->toCheck->setChecked(true);
    ui->fromDateTimeEdit->setDate(QDate::currentDate());
    ui->fromDateTimeEdit->setTime(QTime(0, 0));
    ui->toDateTimeEdit->setDate(QDate::currentDate());
    ui->toDateTimeEdit->setTime(QTime(23, 59, 59, 999));
}

void StudyRegisterWidget::onWlistThisWeek()
{
    ui->fromCheck->setChecked(true);
    ui->toCheck->setChecked(true);
    ui->fromDateTimeEdit->setDate(QDate::currentDate().addDays(-6));
    ui->fromDateTimeEdit->setTime(QTime(0, 0));
    ui->toDateTimeEdit->setDate(QDate::currentDate());
    ui->toDateTimeEdit->setTime(QTime(23, 59, 59, 999));
}

void StudyRegisterWidget::onWlistThisMonth()
{
    ui->fromCheck->setChecked(true);
    ui->toCheck->setChecked(true);
    ui->fromDateTimeEdit->setDate(QDate::currentDate().addMonths(-1));
    ui->fromDateTimeEdit->setTime(QTime(0, 0));
    ui->toDateTimeEdit->setDate(QDate::currentDate());
    ui->toDateTimeEdit->setTime(QTime(23, 59, 59, 999));
}

void StudyRegisterWidget::onWlistClear()
{
    ui->patientIdEdit->clear();
    ui->reqPhysicianCombo->setCurrentIndex(0);
    ui->patientNameEdit->clear();
    ui->modalityCombo->setCurrentIndex(0);
    ui->fromCheck->setChecked(false);
    ui->toCheck->setChecked(false);
}
